package com.cyrus.vueboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyrus.vueboot.mapper.dpt.DepartmentMapper;
import com.cyrus.vueboot.mapper.dpt.DepartmentUserMapper;
import com.cyrus.vueboot.mapper.log.LoginLogMapper;
import com.cyrus.vueboot.pojo.dpt.Department;
import com.cyrus.vueboot.pojo.dpt.DepartmentUser;
import com.cyrus.vueboot.pojo.log.loginLog;
import com.cyrus.vueboot.service.DepartmentService;
import com.cyrus.vueboot.service.LoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/24
 */
@Service
public class DepartmentServiceImpl  extends ServiceImpl<DepartmentMapper,Department> implements DepartmentService{
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DepartmentUserMapper departmentUserMapper;
    @Override
    public IPage search(Integer page, Integer size, String key) {
        IPage<Department> page1 = departmentMapper.selectPage(new Page<Department>(page, size), new QueryWrapper<Department>().lambda().eq(Department::getIsDelete, 0).like(Department::getDptName, key).orderByAsc(Department::getDptLevel));
        return page1;
    }

    @Override
    public void delDepartments(Long[] ids) {
        for (Long id : ids) {
            update(new UpdateWrapper<Department>().lambda().set(Department::getIsDelete, 1).eq(Department::getId, id));
        }

    }

    @Override
    public Department findDetailById(Integer id) {
        Department department = departmentMapper.selectById(id);
        //从部门员工中获取当前部门的所有人数
        Integer departmentUserCount = departmentUserMapper.selectCount(new QueryWrapper<DepartmentUser>().lambda().eq(DepartmentUser::getDptName, department.getDptName()));
        department.setDptCount(departmentUserCount);
        return department;
    }

    @Override
    public void saveNewDpt(Department department) {

        if (department.getBelongDpt() == null) {
            department.setBelongDpt(null);
            department.setDptLevel(1);
        } else {
            department.setDptLevel(2);
        }

        department.setIsDelete(0);
        department.setDptCount(0);
        department.setDptManager(null);

        departmentMapper.insert(department);
    }


}
